<template>
  <ContentWrap :bodyStyle="{ paddingTop: '5px' }">
    <Back :backOption="backOption" />
    <div class="h-full">
      <el-form
        class="top-search"
        label-width="140px"
        :model="formData"
        ref="addFileFormRef"
        :rules="rules"
        @submit.prevent
      >
        <el-row class="row-item" :gutter="40">
          <el-col :span="12">
            <el-form-item label="上级节点" prop="pid">
              <el-cascader
                style="max-width: 400px; width: 100%"
                v-model="formData.pid"
                :clearable="!params.pid"
                :disabled="treeGroupDisable"
                placeholder="请选择上级节点"
                :options="treeGroupData"
                :props="cascaderProps"
                filterable
                :filter-method="sysFilterMethod"
              />
              <!-- @change="treeGroupChange" -->
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="fileGroupType === 1">
            <el-form-item label="新增文件组名称" prop="groupName" class="col-item">
              <ns-input
                style="max-width: 400px; width: 100%"
                v-model="formData.groupName"
                placeholder="请输入文件组名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="formData.groupName">
            <el-form-item label="归属机构" prop="deptId" class="col-item">
              <el-cascader
                ref="deptCascader"
                v-model="formData.deptId"
                placeholder="请选择归属机构"
                :props="depCascaderProps"
                :options="deptList"
                filterable
                clearable
                value-on-clear=""
                :filter-method="sysFilterMethod"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="formData.groupName">
            <el-form-item label="归属系统" prop="sysId" class="col-item">
              <el-cascader
                ref="systemCascader"
                v-model="formData.sysId"
                placeholder="请选择归属系统"
                :props="systemCascaderProps"
                :options="systemList"
                filterable
                clearable
                value-on-clear=""
                :filter-method="sysFilterMethod"
              />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="6" v-if="fileGroupType === 2">
            <el-form-item label="目标文件组" prop="groupId" class="col-item" ref="groupIdRef">
              <el-tree-select
                style="width: 100%"
                placeholder="请选择目标文件组"
                v-model="formData.groupId"
                value-key="id"
                node-key="id"
                :data="childGroup"
                :props="{ label: 'name' }"
                :render-after-expand="false"
                check-strictly
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="">
              <el-radio-group v-model="fileGroupType">
                <el-radio :label="1">新增文件组</el-radio>
                <el-radio :label="2">上传至已有文件组</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col> -->
        </el-row>
        <el-row class="row-item" :gutter="40">
          <el-col :span="12" class="col-item">
            <el-form-item label="上传文件">
              <el-upload
                ref="uploadRef"
                class="upload-wrap"
                v-model:file-list="fileList"
                :action="UPLOAD_URL"
                :auto-upload="true"
                :show-file-list="true"
                :headers="uploadHeaders"
                :limit="10"
                :accept="fileAccept"
                :on-error="submitFormError"
                :on-exceed="handleExceed"
                :on-success="submitFormSuccess"
                :before-upload="handleBefore"
                :on-remove="handleRemove"
                multiple
                drag
              >
                <div>
                  <el-icon color="#ccc" size="35"><UploadFilled /> </el-icon>
                </div>
                <div class="el-upload__text"> 将文件拖到此处，或 <em>点击上传</em> </div>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="col-item">
            <el-row :gutter="10" class="check-row-item" v-for="idx in 3" :key="idx">
              <el-col :span="4">
                <el-checkbox
                  v-model="checkAllList[idx - 1]"
                  @change="(value) => handleAllChecked(idx - 1, value)"
                  >全选</el-checkbox
                >
              </el-col>
              <el-col :span="20">
                <el-checkbox-group
                  v-model="checkedList[idx - 1]"
                  @change="(value) => handleChecked(idx - 1, value)"
                >
                  <el-row :gutter="10">
                    <el-col :span="4" v-for="type in fileTypes[idx - 1]" :key="type">
                      <el-checkbox :label="type" :value="type">{{ type }}</el-checkbox>
                    </el-col>
                  </el-row>
                </el-checkbox-group>
              </el-col>
            </el-row>
          </el-col>
        </el-row>

        <div style="text-align: center">
          <el-button
            type="primary"
            @click="submit"
            :loading="formLoading || isUploading"
            :disabled="formLoading || isUploading"
            >确定</el-button
          >
          <el-button @click="handleClose" :loading="formLoading || isUploading">取消</el-button>
        </div>
      </el-form>
    </div>
  </ContentWrap>
</template>

<script setup lang="ts">
import { sysFilterMethod } from '@/utils/selectFilter'
import Back from '@/components/Back/index.vue'
import { useUpload } from './useUpload'
import { UploadFilled } from '@element-plus/icons-vue'
import { useGroupTree } from '@/hooks/web/useFileTree'
import { createFileManage } from '@/api/develop/file'
import type { FormInstance } from 'element-plus'
import { ElTreeSelect, ElFormItem } from 'element-plus'
import type Node from 'element-plus/es/components/tree/src/model/node'
import { useEmitt } from '@/hooks/web/useEmitt'
import { fileTypes } from './constants'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getSimpleDeptList } from '@/api/system/dept'
import { getSimpleSystemList } from '@/api/asset/taskManage'
import { handleTree } from '@/utils/tree'

const router = useRouter()
const { params } = useRoute()
const message = useMessage() // 消息弹窗
const FILE_MAX_SIZE = 50
const { emitter } = useEmitt()

const { t } = useI18n() // 国际化
const deptList = ref([])
const systemList = ref([])

const addFileFormRef = ref<FormInstance>()
const treeGroupRef = ref<InstanceType<typeof ElTreeSelect>>()
const groupIdRef = ref<InstanceType<typeof ElFormItem>>()

const cascaderProps = ref({
  checkStrictly: true,
  label: 'name',
  value: 'id',
  children: 'children',
  emitPath: false
})

const backOption = reactive({
  title: '新增文件'
})

const data = reactive({
  formData: {
    pid: '0',
    groupName: '',
    deptId: '',
    sysId: ''
  },

  fileGroupType: 1,
  childGroup: []
})
const isRequired = computed(() => {
  return !formData.value.deptId && !formData.value.sysId
})
const rules = computed(() => ({
  pid: [{ required: true, message: '请选择上级节点', rigger: ['blur', 'change'] }],
  groupName: [
    { required: data.formData.pid == '0', message: '请输入文件组名称', rigger: ['blur', 'change'] }
  ],
  groupId: [{ required: true, message: '请选择目标文件组', rigger: ['blur', 'change'] }],
  deptId: [{ required: isRequired.value, message: '归属机构不能为空', trigger: 'change' }],
  sysId: [{ required: isRequired.value, message: '归属系统不能为空', trigger: 'change' }]
}))
const { treeGroupData, reFreshTreeData } = useGroupTree()

if (params.pid) {
  data.formData.pid = params.pid as string
}

const treeGroupDisable = computed(() => {
  return !!params.pid
})

const systemCascaderProps = reactive({
  checkStrictly: true,
  label: 'value',
  value: 'id',
  children: 'children',
  emitPath: false
})
const depCascaderProps = reactive({
  checkStrictly: true,
  label: 'name',
  value: 'id',
  children: 'children',
  emitPath: false // 用于 cascader 组件：在选中节点改变时，是否返回由该节点所在的各级菜单的值所组成的数组，若设置 false，则只返回该节点的值
})

const checkAllList = reactive([true, true, true])

const checkedList = reactive<[string[], string[], string[]]>([
  ['.doc', '.docx', '.ppt', '.pptx', '.wps', '.wpt', '.dps', '.dpt', '.wpp', '.pdf', '.txt'],
  ['.xls', '.xlsx', '.et', '.ett'],
  ['.rar', '.zip', '.7z']
])

const mimeTypes = [
  'application/msword',
  'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  'application/vnd.ms-powerpoint',
  'application/vnd.openxmlformats-officedocument.presentationml.presentation',
  'application/vnd.ms-works',
  'application/vnd.kingsoft-presentation',
  'application/pdf',
  'text/plain',
  'application/vnd.ms-excel',
  'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  'application/vnd.kingsoft-spreadsheet',
  'application/x-rar-compressed',
  'application/zip',
  'application/x-7z-compressed',
  'application/x-tika-msoffice'
]

function handleAllChecked(idx: number, val: any) {
  checkedList[idx] = val ? fileTypes[idx] : []
}

function handleChecked(idx: number, arr: any[]) {
  const checkedCount = arr.length
  checkAllList[idx] = checkedCount === fileTypes[idx].length
}

async function getDeptList() {
  const data = await getSimpleDeptList()
  deptList.value = data
}
async function getSystemList() {
  const data = await getSimpleSystemList()
  systemList.value = handleTree(data, 'id', 'pid')
}

const {
  uploadHeaders,
  UPLOAD_URL,
  fileList, // 文件列表
  submitFormSuccess,
  handleExceed,
  submitFormError,
  fileAccept,
  isUploading,
  handleRemove
} = useUpload(checkedList)

const { formData, fileGroupType, childGroup } = toRefs(data)

const formLoading = ref(false)

const uploadRef = ref()

const handleBefore = (rawFile) => {
  const fileSuffix = '.' + rawFile.name.substring(rawFile.name.lastIndexOf('.') + 1)
  if (rawFile.size / 1024 / 1024 > FILE_MAX_SIZE) {
    ElMessage.error('文件大小不能超过50MB')
    return false
  }
  if (checkedList.every((item) => !item.includes(fileSuffix))) {
    console.log('文件类型不符合要求')
    ElMessage.error('文件类型不符合要求')
    return false
  }
  isUploading.value = true
  return true
}

async function submit() {
  await addFileFormRef.value?.validate()
  formLoading.value = true
  try {
    const fileInfos = fileList.value.reduce((acc, cur: any) => acc.concat(cur.response.data), [])
    const eTypes = getErrorFileType(fileInfos)
    if (eTypes.length > 0) {
      ElMessageBox.alert(`压缩包中存在无法解析的文件：${eTypes.join(',\n')}`, '系统提示', {
        confirmButtonText: '确定',
        type: 'warning'
      })
      return
    }
    if (!formData.value.groupName) {
      formData.value.deptId = ''
      formData.value.sysId = ''
    }
    await createFileManage({
      ...toRaw(formData.value),
      pid: formData.value.pid ? formData.value.pid : 0,
      fileInfos: fileInfos.map((file: any) => {
        return {
          name: file.name,
          type: file.type,
          url: file.url,
          size: file.size
        }
      })
    })
    message.success(t('common.createSuccess'))
    emitter.emit('addFileSuccess')
    reFreshTreeData()
    handleClose()
  } catch (error) {
    console.log('error', error)
  } finally {
    formLoading.value = false
  }
}

//寻找是否含有不符合的文件类型
function getErrorFileType(files: any[]) {
  const list_ = [] as any[]

  files.forEach((file) => {
    if (!mimeTypes.includes(file.type)) {
      list_.push(file.name)
    }
  })
  return list_
}

function treeGroupChange(id) {
  if (!id) return
  groupIdRef.value?.resetField()
  const node: Node = treeGroupRef.value?.getNode(id)
  data.childGroup = node.data.children
}

const handleClose = () => {
  router.push({ name: 'DevelopFile' })
}

onMounted(() => {
  reFreshTreeData()
  getSystemList()
  getDeptList()
  // setTimeout(() => {
  //   treeGroupChange(params.pid || '0')
  // }, 500)
})
</script>

<style lang="scss" scoped>
.h-full {
  padding: 20px;
}
.row-item {
  padding: 10px 0;

  .col-item {
  }
}
.upload-wrap {
  width: 100%;
  :deep(.el-upload-dragger) {
    height: 180px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
  }
}
.check-row-item {
  padding: 10px 0;
}
.file-list {
  width: 100%;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  padding: 10px 20px;
}
.file-item {
  color: rgb(96, 98, 102);
  display: flex;
  align-items: center;
  :deep(.el-icon) {
    // position: relative;
    // top: 1px;
    margin-right: 5px;
  }
}
.del-file {
  margin-left: auto;
  cursor: pointer;
}
.pro-wrap {
  width: 100%;
  padding: 0 5%;
}
:deep(.el-upload-list__item) {
  .el-icon {
    font-size: 20px;
  }
}
</style>
